package org.jaaksi.kottlindemo.coroutines

import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import libcore.eventbus.launchWhenStateAtLeast

object TestLaunch {

    // runBlocking会阻塞当前线程（不管context是什么），直到runBlocking中的内容执行完毕，用于同步.
    private fun testRunBlocking() {
        runBlocking(Dispatchers.IO) {
            println(">> 1 runBlocking thread = ${Thread.currentThread()}")
            delay(1000)
            println(">>2 coroutine end")
        }
        println(">>3 Thread sleep start")
    }

    // GlobalScope.launch的默认调度器是共享的后台线程池。
    private fun testGlobalScope() {
        GlobalScope.launch/*(Dispatchers.IO)*/ {
            println(">> 1 thread = ${Thread.currentThread()}")
            delay(1000)
            println(">>2 coroutine end")
        }
        println(">>3 Thread sleep start")
    }

    /**
     * MainScope方法实现：ContextScope(SupervisorJob() + Dispatchers.Main)
     * fixme 要记得销毁
     * fixme MainScope().launch -> 3 4 1 2。可以看到这个协程是在主线程的代码执行完毕后才执行
     */
    fun testMainScope() {
        val job = MainScope().launch {
            println(">>1 delay")
            // 协程被挂起，主线程继续执行下面的代码
            delay(10)
//                withContext(Dispatchers.IO){
//                    println(">> with context io")
//                }
            println(">>2 coroutine end")
        }
        println(">>3 Thread sleep start")
        Thread.sleep(1000)
        println(">>4 Thread sleep end")
        job.cancel()

    }

    // lifecycleScope.launch -> 1 3 4 2，如果lifecycleScope.launch(Dispatchers.Main)那么就和MainScope().launch一样了
    // Lifecycle.coroutineScope传入的context是SupervisorJob() + Dispatchers.Main.immediate
    fun testLifecycleScope(lifecycleOwner: LifecycleOwner) {
        lifecycleOwner.lifecycleScope.launch(/*Dispatchers.Main*/) {
            println(">>1 delay")
            // 协程被挂起，主线程继续执行下面的代码
            delay(10)
//                withContext(Dispatchers.IO){
//                    println(">> with context io")
//                }
            println(">>2 coroutine end")
        }
        println(">>3 Thread sleep start")
        Thread.sleep(1000)
        println(">>4 Thread sleep end")
        lifecycleOwner.lifecycleScope.launch {

        }


    }

//    fun testLaunchWhenResumed(lifecycleOwner: LifecycleOwner) {
//        lifecycleOwner.lifecycleScope.launchWhenResumed {
//
//        }
//        lifecycleOwner.launchWhenStateAtLeast()
//    }


}